package org.ch02.test00.demo05;

import java.lang.reflect.Method;

/**
 * @author ZQX
 * @date 2025-03-19
 */
public class Email {
    public static String getEmail01(String email) {
        if (!email.contains("@")) {
            return null;
        } else {
            return email.substring(0, email.indexOf("@"));
        }
    }

    public static String getEmail02(String email) {
        try {
            // 获取 String 类要调用的方法
            Method containsMethod = String.class.getMethod("contains", CharSequence.class);
            Method substringMethod = String.class.getMethod("substring", int.class, int.class);
            Method indexOfMethod = String.class.getMethod("indexOf", String.class);

            // email.contains("@")
            Object blObj = containsMethod.invoke(email, "@");

            if (blObj instanceof Boolean) {
                boolean isIncludeAt = (boolean) blObj;
                if (!isIncludeAt) {
                    return null;
                }

                // email.indexOf("@")
                Object atObj = indexOfMethod.invoke(email, "@");
                if (atObj instanceof Integer) {
                    int atIndex = (int) atObj;

                    // email.substring(0,atIndex) ;
                    Object nameObj = substringMethod.invoke(email, 0, atIndex);

                    if (nameObj instanceof String) {
                        return (String) nameObj;
                    }
                }

            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static String getEmail03(String email) {
        try {
            // 获取 String 类要调用的方法
            Method containsMethod = String.class.getMethod("contains", CharSequence.class);
            Method substringMethod = String.class.getMethod("substring", int.class, int.class);
            Method indexOfMethod = String.class.getMethod("indexOf", String.class);

            // email.contains("@")
            boolean isIncludeAt = (Boolean)containsMethod.invoke(email, "@");
            if (!isIncludeAt) {
                return null;
            }

            // email.indexOf("@")
            int atIndex = (Integer)indexOfMethod.invoke(email, "@");

            // email.substring(0,atIndex) ;
            return (String)substringMethod.invoke(email, 0, atIndex);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
